package cn.smdq.ch.upms.admin.pay.channel.support;

import cn.smdq.ch.common.core.exception.BaseException;
import cn.smdq.ch.common.util.UrlUtil;
import cn.smdq.ch.upms.admin.pay.channel.param.AliPayPrePayResponse;
import cn.smdq.ch.upms.admin.pay.channel.param.AliPayRequestParam;
import cn.smdq.ch.upms.admin.pay.channel.param.PrePayResponse;
import cn.smdq.ch.upms.admin.pay.type.PayType;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;

/**
 * @author shuimodanqing
 * create at:  2019/1/29  2:01 PM
 * @description 支付宝手机网页支付
 */
public class AliPayMobileWapChannel extends BaseAliPayChannel {

    public AliPayMobileWapChannel(JSONObject jsonObject) {
        super(jsonObject);
    }

    @Override
    public PrePayResponse pay(PayType payType) {
        AlipayTradeWapPayRequest request;
        try {
            request = buildRequest();
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
            System.out.println("response: " + response.getBody());
            return new PrePayResponse.Builder()
                    .payType(payType)
                    .response(buildAliWapPrepayResponse(response))
                    .requestParam(request.toString()).build();
        } catch (AlipayApiException e) {
            throw new BaseException("支付失败：" + e.getErrCode() + " : " + e.getErrMsg());
        }
    }

    private AlipayTradeWapPayRequest buildRequest() {
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();

        AliPayRequestParam requestParam = payRequestParamToUse;

        model.setBody(UrlUtil.encode(requestParam.getBody(), "utf-8"));
        model.setSubject(UrlUtil.encode(requestParam.getSubject(), "utf-8"));
        model.setOutTradeNo(requestParam.getOutTradeNo());
        //     model.setTimeoutExpress(requestParam.getTimeoutExpress());
        //     model.setTimeExpire(requestParam.getTimeExpire());
        model.setTotalAmount(requestParam.getTotalFee());
        model.setProductCode(requestParam.getProductCode());
        model.setGoodsType(requestParam.getGoodsType());
        request.setBizModel(model);
        request.setNotifyUrl(requestParam.getNotifyUrl());
        return request;
    }

    private static Object buildAliWapPrepayResponse(AlipayTradeWapPayResponse response) {
        return new AliPayPrePayResponse.Builder()
                .outTradeNo(response.getOutTradeNo())
                .tradeNo(response.getTradeNo())
                .body(response.getBody())
                .build();
    }
}
